package LeetCode.leetcode541;

import java.util.Arrays;

public class Main {
    /**
     * 自写 超时？
     *
     * @param s
     * @param k
     * @return
     */
    public String reverseStr(String s, int k) {

        char[] arr = s.toCharArray();
        int n = s.length() / (2 * k);
        int left;
        int right;
        char temp;
        for (int i = 0; i < n; i++) {
            left = i * 2 * k;
            right = left + k - 1;
            while (left < right) {
                temp = arr[right];
                arr[right] = arr[left];
                arr[left] = temp;
            }
        }
        if ((arr.length - n * 2 * k) > k) {
            left = 2 * n * k;
            right = left + k - 1;
            while (left < right) {
                temp = arr[right];
                arr[right] = arr[left];
                arr[left] = temp;
            }
        } else {
            left = 2 * n * k;
            right = arr.length - 1;
            while (left < right) {
                temp = arr[right];
                arr[right] = arr[left];
                arr[left] = temp;
            }
        }
        return s = String.valueOf(arr);
    }

    /**
     * 题解
     *
     * @param s
     * @param k
     * @return
     */
    public String reverseStr2(String s, int k) {
        char[] chars = s.toCharArray();
        int len = s.length();
        int left = 0;
        while (left < len) {
            int right = left + k - 1;
            reverse(chars, left, Math.min(right, len - 1));
            left += 2 * k;
        }
        return String.valueOf(chars);
    }

    private void reverse(char[] c, int left, int right) {
        while (left < right) {
            char temp = c[left];
            c[left] = c[right];
            c[right] = temp;
            left++;
            right--;
        }
    }

    /**
     * review
     *
     * @param s
     * @param k
     * @return
     */
    public String reverseStr3(String s, int k) {

        int l = 0;
        int r = s.length();
        char[] a = s.toCharArray();
        while (l < r) {
            int n = l + k - 1;
            reverse(a, l, Math.min(n, r - 1));
            l += 2 * k;
        }
        return String.valueOf(a);
    }

}
